﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AB_SD_Entities;
using AB_SD_BusinessLogic;

namespace AB_SD_MockProject
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // if there are cookies in client browser
            if (Request.Cookies["CurrentUser"] != null)
            {
                // store sessions by cookies value
                Session["CurrentUser"] = Request.Cookies["CurrentUser"].Value.ToString();
                if (Request.Cookies["IsSuper"] != null)
                {
                    if (Boolean.Parse(Request.Cookies["IsSuper"].Value))
                    {
                        Session["IsSuper"] = Boolean.TrueString;
                        Response.Redirect("Default.aspx");
                    }
                }
                Session["IsAdmin"] = Boolean.FalseString;
                Response.Redirect("Default.aspx");
            }
        }

        /// <summary>
        /// Validate login (is valid login or not)
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        protected void vldLogin_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = UserBUS.IsValidLogin(txtUsername.Text, txtPassword.Text);            
        }

        /// <summary>
        /// Button Login Clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdLogin_Click(object sender, EventArgs e)
        {
            // if form is valid
            if (Page.IsValid)
            {
                User user = UserBUS.Select(txtUsername.Text);

                // store sessions
                Session["CurrentUser"] = txtUsername.Text;
                Session["IsSuper"] = user.IsSuper.ToString();

                // if "Remember me" is checked
                if (chkRemember.Checked)
                {
                    // Store cookies
                    Response.Cookies["CurrentUser"].Value = txtUsername.Text;
                    Response.Cookies["CurrentUser"].Expires = DateTime.Now.AddDays(30);
                    Response.Cookies["IsSuper"].Value = user.IsSuper.ToString();
                    Response.Cookies["IsSuper"].Expires = DateTime.Now.AddDays(30);
                }
                
                // redirect to home page
                Response.Redirect("Default.aspx");
            }
        }
    }    
}